<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-row :gutter="20">
              <a-col :span="5">
                <a-form-item field="deviceName" label="设备">
                  <!-- deviceName -->
                  <a-input
                    v-model="formModel.deviceName"
                    placeholder="请输入设备名称或者设备分类名"
                    allow-clear
                  />
                </a-form-item>
              </a-col>

              <a-col :span="5">
                <a-space :size="18">
                  <a-button type="primary" @click="onPageChange(1)">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                  <a-button type="primary" @click="openAdd">
                    <template #icon>
                      <icon-plus />
                    </template>
                    新增
                  </a-button>
                  <a-button
                    type="primary"
                    @click="plstart('1')"
                    status="success"
                  >
                    批量启用
                  </a-button>
                  <a-button
                    type="primary"
                    @click="plstart('2')"
                    status="warning"
                  >
                    批量禁用
                  </a-button>
                  <a-button @click="openUpload"> 批量导入 </a-button>
                  <a-button type="primary" @click="pldel" status="danger">
                    批量删除
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <!-- <a-divider style="margin-top: 0" /> -->

      <a-table
        ref="userList"
        row-key="deviceId"
        v-model:selectedKeys="deviceIdd"
        :loading="loading"
        page-position="bottom"
        :pagination="pagination"
        :row-selection="rowSelections"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #option="{ record }">
          <a-space :size="18">
            <a-button @click="openEdit(record)" type="primary"> 编辑 </a-button>
            <a-button status="danger" @click="openDelete(record)">
              删除
            </a-button>
          </a-space>
        </template>
        <template #disabled="{ record }">
          <a-space :size="18" @click="disabledfn(record)">
            <div
              :class="record.disableds == true ? 'starts' : 'starts startss'"
            >
              {{ record.disableds == true ? '启用' : '禁用' }}
            </div>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
    >
      <template #title> 设备 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-row style="margin-bottom: 16px">
          <a-col>
            <a-form-item field="deviceName" label="设备名称">
              <a-input
                v-model="addForm.deviceName"
                size="large"
                placeholder="请输入设备名称"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row style="margin-bottom: 16px">
          <a-col>
            <a-form-item field="deviceType" label="设备分类">
              <a-input
                v-model="addForm.deviceType"
                size="large"
                placeholder="请输入设备分类名"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col>
            <a-form-item field="disabled" label="启用状态">
              <!--     :checked-value="1"
                :unchecked-value="9" -->
              <a-switch v-model="addForm.disabled" @change="changes">
                <template #checked> ON </template>
                <template #unchecked> OFF </template>
              </a-switch>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <a-modal
      class="df"
      v-model:visible="uploadShow"
      @cancel="uploadCancel"
      :on-before-ok="uploadCheck"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 导入设备 </template>
      <a-form ref="uploadModel" :rules="uploadRules" :model="uploadForm">
        <a-row style="margin-bottom: 16px">
          <a-form-item field="file" label="文件">
            <a-upload
              class="upload_box"
              @change="onChange"
              accept=".xls,.xlsx"
              ref="uploadRef"
              :auto-upload="false"
              :limit="1"
            >
              <template #upload-button>
                <a-space>
                  <a-button type="primary">选择附件</a-button>
                  <a-button @click.stop="downloadTemplate">下载模板</a-button>
                </a-space>
              </template>
            </a-upload>
          </a-form-item>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts">
  export default {
    name: 'user',
  };
</script>
<script lang="ts" setup>
  import { ref, reactive, computed } from 'vue';
  import useLoading from '@/hooks/loading';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message, Modal } from '@arco-design/web-vue';
  import {
    deviceList,
    deviceSave,
    deviceUpdate,
    deviceRemove,
    disabledActive,
    downloadTemplate,
    importClass,
  } from '@/api/device';
  const uploadCancel = () => {
    uploadShow.value = false;
  };

  const plstart = (i) => {
    if (i == '1') {
      if (deviceIdd.value.length == 0) {
        Modal.confirm({
          title: '提示',
          content: '请先选中要启用的设备？',
        });
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定批量启用吗',
          onOk() {
            Promise.all(
              deviceIdd.value.map((timetableId) => {
                return disabledActive({
                  deviceId: timetableId,
                  disabled: '1',
                }).then((res) => {
                  if (res.code == '200') {
                    return true; // 标记删除成功
                  } else {
                    fetchData();
                    throw new Error('启用失败');
                  }
                });
              })
            )
              .then((results) => {
                // 检查所有结果是否都为 true，表示删除成功
                if (results.every((result) => result === true)) {
                  // 如果所有删除成功，显示成功提示
                  Message.success({
                    content: '启用成功',
                  });

                  // 然后重新获取数据
                  fetchData();
                }
              })
              .catch((err) => {
                fetchData();
                console.error('失败:', err);
              });
          },
        });
      }
    }
    if (i == '2') {
      if (deviceIdd.value.length == 0) {
        Modal.confirm({
          title: '提示',
          content: '请先选中要禁用的设备？',
        });
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定批量禁用吗？',
          onOk() {
            Promise.all(
              deviceIdd.value.map((timetableId) => {
                return disabledActive({
                  deviceId: timetableId,
                  disabled: '9',
                }).then((res) => {
                  if (res.code == '200') {
                    return true; // 标记删除成功
                  } else {
                    fetchData();
                    throw new Error('禁用失败');
                  }
                });
              })
            )
              .then((results) => {
                // 检查所有结果是否都为 true，表示删除成功
                if (results.every((result) => result === true)) {
                  // 如果所有删除成功，显示成功提示
                  Message.success({
                    content: '禁用成功',
                  });

                  // 然后重新获取数据
                  fetchData();
                }
              })
              .catch((err) => {
                fetchData();
                console.error('禁用失败:', err);
              });
          },
        });
      }
    }
  };
  const pldel = () => {
    if (deviceIdd.value.length == 0) {
      Modal.confirm({
        title: '提示',
        content: '请先选中要删除的设备？',
      });
    } else {
      Modal.confirm({
        title: '提示',
        content: '确定批量删除吗',
        onOk() {
          Promise.all(
            deviceIdd.value.map((timetableId) => {
              return deviceRemove({
                deviceId: timetableId,
              }).then((res) => {
                if (res.code == '200') {
                  Message.success({
                    content: '删除成功',
                  });
                  fetchData();
                }
              });
            })
          )
            .then((results) => {
              // 检查所有结果是否都为 true，表示删除成功
              if (results.every((result) => result === true)) {
                // 如果所有删除成功，显示成功提示
                Message.success({
                  content: '删除成功',
                });

                // 然后重新获取数据
                fetchData();
              }
            })
            .catch((err) => {
              fetchData();
              console.error('失败:', err);
            });
        },
      });
    }
  };
  const uploadCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          let formData = new FormData();
          formData.append('file', uploadForm.value.file);
          importClass(formData).then((res) => {
            if (res.code == '200') {
              Message.success({
                //   content: res.message,
                content: '新增成功',
              });
              reset();
              done(true);
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const uploadRules = {
    file: [
      {
        required: true,
        message: '请选择附件',
      },
    ],
  };
  const onChange = (fileList) => {
    if (fileList && fileList.length > 0) {
      uploadForm.value.file = fileList[0].file;
    } else {
      uploadForm.value.file = null;
    }
  };
  const deviceIdd = ref([]);
  const generateUploadModel = () => {
    return {
      file: null,
      // deptId: '',
    };
  };

  const uploadForm = ref(generateUploadModel());
  const uploadShow = ref(false);
  const uploadModel = ref();
  const openUpload = () => {
    uploadForm.value = generateDataModel();
    uploadShow.value = true;
  };
  const disabledfn = (record) => {
    // console.log('record', record);

    const disableds = ref('');
    if (record.disabled == true) {
      disableds.value = '9';
      console.log('执行了1');
    } else {
      disableds.value = '1';
      console.log('执行了9');
    }
    disabledActive({
      disabled: disableds.value,
      deviceId: record.deviceId,
    }).then((res) => {
      if (res.code == '200') {
        Message.success({
          content: res.message,
        });
        // fetchData();
        reset();
      } else {
      }
    });
  };
  const { loading, setLoading } = useLoading(true);
  const addShow = ref(false);

  const handleCancel = () => {
    addShow.value = false;
  };
  const generateDataModel = () => {
    return {
      deviceName: '',
      disabled: 'false',
      deviceId: '',
    };
  };
  function changes(value) {
    addForm.value.disabled = value;
  }
  const openEdit = (item) => {
    addShow.value = true;
    addForm.value.deviceId = item.deviceId;
    addForm.value.deviceType = item.deviceType;

    if (item.disabled == 1) {
      addForm.value.disabled = true;
    } else {
      addForm.value.disabled = false;
    }

    console.log('是否选中', addForm.value.disabled, item.disabled);

    addForm.value.deviceName = item.deviceName;
  };
  //   初始化表单
  const addForm = ref(generateDataModel());

  //   新增 和修改
  const handleCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.deviceId) {
            const disableds = ref('');
            if (addForm.value.disabled == true) {
              disableds.value = '1';
            } else {
              disableds.value = '9';
            }
            deviceUpdate({
              deviceName: addForm.value.deviceName,
              disabled: disableds.value,
              deviceId: addForm.value.deviceId,
            }).then((res) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '编辑成功',
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          } else {
            const disableds = ref('');
            if (addForm.value.disabled == true) {
              disableds.value = '1';
            } else {
              disableds.value = '9';
            }
            deviceSave({
              deviceName: addForm.value.deviceName,
              disabled: disableds.value,
            }).then((res) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '添加成功',
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          }
        } else {
          done(false);
        }
      }
    );
  };
  //   表单规则
  const rules = reactive({
    deviceName: [
      {
        required: true,
        message: '请输入设备名称',
      },

      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
    disabled: [
      {
        required: true,
        message: '请选择是否启用',
      },
    ],
  });

  //   新增

  const openAdd = () => {
    addForm.value = generateDataModel();
    addShow.value = true;
  };

  const openDelete = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        deviceRemove({
          deviceId: item.deviceId,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              content: '删除成功',
            });
            fetchData();
          }
        });
      },
    });
  };

  const rowSelections = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '设备id',
      dataIndex: 'deviceId',
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
    },
    {
      title: '设备分类',
      dataIndex: 'deviceType',
    },
    {
      title: '启动状态',
      dataIndex: 'disabled',
      slotName: 'disabled',
      align: 'center',
      //   slots: 'content',
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
    },

    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);

  const generateFormModel = () => {
    return {
      deviceName: '',
    };
  };

  const formModel = ref(generateFormModel());
  const renderData = ref([]);
  const userList = ref();

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      deviceList(data).then((res) => {
        let list = res.data.list || [];

        renderData.value = list;
        pagination.total = res.data.total;
        pagination.current = res.data.current;

        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };

  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };
  fetchData();
  const addModel = ref();
</script>
<style>
  .addmens {
    /* position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%); */
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .addmens button {
    margin: 10px 20px;
  }
  .starts {
    cursor: pointer;
    color: #0f51e7;
  }
  .startss {
    color: red;
  }
</style>
